package com.company.cloud.mall.modules.app.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.acct.modules.api.constant.AcctOpTypeEnum;
import com.company.cloud.acct.modules.api.constant.AcctTypeEnum;
import com.company.cloud.acct.modules.api.request.AcctOpRequest;
import com.company.cloud.acct.modules.api.service.AccountRemoteService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.mall.constant.MallErrorEnum;
import com.company.cloud.mall.constant.PayMethodEnum;
import com.company.cloud.mall.constant.ShopConstant.PayActionTypeEnum;
import com.company.cloud.mall.constant.ShopConstant.PayConfirmWay;
import com.company.cloud.mall.modules.api.constant.OrderReturnStateEnum;
import com.company.cloud.mall.modules.api.constant.OrderStateEnum;
import com.company.cloud.mall.modules.api.response.OrderReturnsModel;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsApplyParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsCheckParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsReceiveParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsRefundParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsSendParam;
import com.company.cloud.mall.modules.app.service.ShopAfterSaleReturnsService;
import com.company.cloud.mall.modules.app.service.ShopOnlinePayService;
import com.company.cloud.mall.modules.app.utils.AfterOrderUtil;
import com.company.cloud.mall.modules.base.entity.OrderInfo;
import com.company.cloud.mall.modules.base.entity.OrderItem;
import com.company.cloud.mall.modules.base.entity.OrderLog;
import com.company.cloud.mall.modules.base.entity.OrderPayment;
import com.company.cloud.mall.modules.base.entity.OrderRefunds;
import com.company.cloud.mall.modules.base.entity.OrderReturns;
import com.company.cloud.mall.modules.base.service.OrderInfoService;
import com.company.cloud.mall.modules.base.service.OrderItemService;
import com.company.cloud.mall.modules.base.service.OrderLogService;
import com.company.cloud.mall.modules.base.service.OrderPaymentService;
import com.company.cloud.mall.modules.base.service.OrderRefundsService;
import com.company.cloud.mall.modules.base.service.OrderReturnsService;
import com.company.cloud.mall.modules.bus.producer.ShopOrderProducer;
import com.company.cloud.mall.modules.utils.ShopNoUtils;
import com.company.cloud.mall.modules.utils.ShopOrderConvertUtils;
import com.company.cloud.pay.modules.api.constant.PayRefundStateEnum;
import com.company.cloud.pay.modules.api.constant.PayStateEnum;
import com.company.common.server.constant.IRelBusiType;

import cn.hutool.core.date.DateUtil;

/**
 * 订单退货退款
 * */
@Service
public class ShopAfterSaleReturnsServiceImpl implements ShopAfterSaleReturnsService{

	@Autowired
	private OrderReturnsService orderReturnsService;
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private OrderItemService orderItemService;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private OrderPaymentService orderPaymentService;
	@Autowired
	private AccountRemoteService accountRemoteService;
	@Autowired
	private OrderRefundsService orderRefundsService;
	@Autowired
	private ShopOnlinePayService shopOnlinePayService;
	@Autowired
	private ShopOrderProducer shopOrderProducer;
	
	
	/**新增*/
	@Transactional
	@Override
	public void add(OrderReturnsApplyParam params, LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		OrderItem orderItem=orderItemService.getById(params.getOrderItemId());
		if(null == orderItem) {
			throw new BusinessException(MallErrorEnum.Order_Item_Null);
		}
		if(YNEnum.NO.getCode().equals(orderItem.getIsExchangePurchase())) {
			throw new BusinessException(MallErrorEnum.Order_After_Product_Not);
		}
		OrderInfo order=orderInfoService.getById(orderItem.getOrderSn());
		if(null == order) {
			throw new BusinessException(MallErrorEnum.Order_Null);
		}
		
		if(userInfo.getId().intValue()!=order.getUserId().intValue()) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}

		if(OrderStateEnum.OSE_Pay.getCode().equals(order.getStatus())
				||OrderStateEnum.OSE_Check.getCode().equals(order.getStatus())
				||OrderStateEnum.OSE_Send.getCode().equals(order.getStatus()) 
				||OrderStateEnum.OSE_Close.getCode().equals(order.getStatus()) 
				) {
			throw new BusinessException(MallErrorEnum.Order_After_Not);
		}
		
		//判断退款金额
		BigDecimal reFund=order.getFund().subtract(order.getRefundFund());
		if(params.getFund().doubleValue()>reFund.doubleValue()) {
			throw new BusinessException(MallErrorEnum.Order_After_Fund);
		}
		//判断退款数量
		int reNum= orderItem.getQuantity()-orderItem.getReturnedQuantity();
		if(params.getQuantity()>reNum) {
			throw new BusinessException(MallErrorEnum.Order_After_Num);
		}
		//判断有没进行中的售后
		List<OrderRefunds> orderRefundsList=orderRefundsService.list(new QueryWrapper<OrderRefunds>()
				.eq("order_sn", orderItem.getOrderSn())
				.eq("order_item_id", orderItem.getId()));
		List<OrderReturns> orderReturnsList=orderReturnsService.list(new QueryWrapper<OrderReturns>()
				.eq("order_sn", orderItem.getOrderSn())
				.eq("order_item_id", orderItem.getId()));
		
		if(!AfterOrderUtil.validateOrderIng(orderRefundsList, orderReturnsList)) {
			throw new BusinessException(MallErrorEnum.Order_After_Ing);
		}
		
		
		String sn=ShopNoUtils.getOrderReturn();
		OrderReturns entity=new OrderReturns();
		entity.setSn(sn);
		entity.setCompanyNo(order.getCompanyNo());
		entity.setMainCompanyNo(order.getMainCompanyNo());
		entity.setUserId(order.getUserId());
		
		entity.setReason(params.getReason());
		entity.setFund(params.getFund());
		entity.setMemo(params.getMemo());
		entity.setCertificate(StrSplitUtils.list2string(params.getCertificate()));
		
		entity.setOrderSn(order.getSn());
		entity.setOrderItemId(orderItem.getId());
		entity.setQuantity(params.getQuantity());
		entity.setProductNo(orderItem.getProductNo());
		entity.setMainProductNo(orderItem.getMainProductNo());
		entity.setSkuNo(orderItem.getSkuNo());
		entity.setMainSkuNo(orderItem.getMainSkuNo());
		entity.setName(orderItem.getName());
		entity.setThumbnail(orderItem.getThumbnail());
		entity.setSpecifications(orderItem.getSpecifications());
		entity.setState(OrderReturnStateEnum.ORFPS_Apply.getCode());
		entity.setStartDate(LocalDateTime.now());
		entity.addCreateParam(userInfo);
		orderReturnsService.save(entity);

		orderItem.setReturnedQuantity(orderItem.getReturnedQuantity()+params.getQuantity());
		orderItemService.updateById(orderItem);
		
		order.setRefundFund(order.getRefundFund().add(params.getFund()));
		order.addEditParam(userInfo);
		orderInfoService.updateById(order);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.setMemo(entity.getMemo());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}
	
	/**撤销*/
	@Transactional
	@Override
	public void cancel(String sn,LoginSimpleUserInfo userInfo) {
		OrderReturns entity=orderReturnsService.getById(sn);
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		
		if(userInfo.getId().intValue()!=entity.getUserId().intValue()) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}
		
		if(OrderReturnStateEnum.ORFPS_Apply.getCode().equals(entity.getState()) 
				||OrderReturnStateEnum.ORFPS_Check_Success.getCode().equals(entity.getState())  
				||OrderReturnStateEnum.ORFPS_Check_Fail.getCode().equals(entity.getState())  ) {}else {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		
		entity.setState(OrderReturnStateEnum.ORFPS_Cancel.getCode());
		entity.setEndDate(LocalDateTime.now());
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		
		OrderInfo order=orderInfoService.getById(entity.getOrderSn());
		order.setRefundFund(order.getRefundFund().subtract(entity.getFund()));
		order.addEditParam(userInfo);
		orderInfoService.updateById(order);
		
		OrderItem orderItem=orderItemService.getById(entity.getOrderItemId());
		orderItem.setReturnedQuantity(orderItem.getReturnedQuantity()-entity.getQuantity());
		orderItemService.updateById(orderItem);
		
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
		
	}
	
	
	/**审核*/
	@Transactional
	@Override
	public void check(OrderReturnsCheckParam params,LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		OrderReturns entity=orderReturnsService.getById(params.getSn());
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		if(!userInfo.getCompanyNo().equals(entity.getMainCompanyNo())) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}
		if(!OrderReturnStateEnum.ORFPS_Apply.getCode().equals(entity.getState())   ) {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		if(YNEnum.YES.getCode().equals(params.getStatus())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Check_Success.getCode());
			entity.setConsigneeName(params.getConsigneeName());
			entity.setConsigneePhone(params.getConsigneePhone());
			entity.setConsigneeAddr(params.getConsigneeAddr());
		}else if(YNEnum.NO.getCode().equals(params.getStatus())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Check_Fail.getCode());
			entity.setEndDate(LocalDateTime.now());
		}
		
		if(StringUtils.hasText(params.getMemo())) {
			if(StringUtils.isEmpty(entity.getRemark())) {
				entity.setRemark(params.getMemo());
			}else {
				entity.setRemark(entity.getRemark()+"/n"+params.getMemo());
			}
		}
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.setMemo(params.getMemo());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		
		if(YNEnum.NO.getCode().equals(params.getStatus())) {
			OrderInfo order=orderInfoService.getById(entity.getOrderSn());
			order.setRefundFund(order.getRefundFund().subtract(entity.getFund()));
			order.addEditParam(userInfo);
			orderInfoService.updateById(order);
			
			OrderItem orderItem=orderItemService.getById(entity.getOrderItemId());
			orderItem.setReturnedQuantity(orderItem.getReturnedQuantity()-entity.getQuantity());
			orderItemService.updateById(orderItem);
		}
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}
	
	/**发货*/
	@Transactional
	@Override
	public void send(OrderReturnsSendParam params, LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		OrderReturns entity=orderReturnsService.getById(params.getSn());
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		if(userInfo.getId().intValue()!=entity.getUserId().intValue()) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}
		if(!OrderReturnStateEnum.ORFPS_Check_Success.getCode().equals(entity.getState())   ) {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		entity.setState(OrderReturnStateEnum.ORFPS_Send.getCode());
		entity.setSendDate(LocalDateTime.now());
		entity.setTrackingNo(params.getTrackingNo());
		entity.setDeliveryCorpName(params.getDeliveryCorpName());
		entity.setDeliveryCorpCode(params.getDeliveryCorpCode());
		entity.setFreight(params.getFreight());
		entity.setShipper(params.getShipper());
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.setMemo(params.getMemo());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
		
	}
	
	/**收货*/
	@Transactional
	@Override
	public void receive(OrderReturnsReceiveParam params, LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		OrderReturns entity=orderReturnsService.getById(params.getSn());
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		if(!userInfo.getCompanyNo().equals(entity.getMainCompanyNo())) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}
		if(OrderReturnStateEnum.ORFPS_Check_Success.getCode().equals(entity.getState())  
			|| OrderReturnStateEnum.ORFPS_Send.getCode().equals(entity.getState())	) {}else {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		
		BigDecimal subFund=null;
		if(YNEnum.YES.getCode().equals(params.getStatus())) {
			if(!CheckUtils.hasBigDecimal(params.getFund())) {
				throw new BusinessException(BaseReturnEnum.PARAM_NULL);
			}
			if(params.getFund().doubleValue()>entity.getFund().doubleValue()) {
				throw new BusinessException(MallErrorEnum.Order_After_Fund);
			}
			if(OrderReturnStateEnum.ORFPS_Check_Success.getCode().equals(entity.getState())	) {
				entity.setSendDate(LocalDateTimeUtils.parse_yyyyMMdd(params.getSendDate()));
				entity.setTrackingNo(params.getTrackingNo());
				entity.setDeliveryCorpName(params.getDeliveryCorpName());
				entity.setDeliveryCorpCode(params.getDeliveryCorpCode());
				entity.setFreight(params.getFreight());
				entity.setShipper(params.getShipper());
			}
			if(params.getFund().doubleValue()!=entity.getFund().doubleValue()) {
				subFund=entity.getFund().subtract(params.getFund());
				entity.setFund(params.getFund());
			}
			entity.setState(OrderReturnStateEnum.ORFPS_Receiving.getCode());
		}else if(YNEnum.NO.getCode().equals(params.getStatus())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Check_Fail.getCode());
			entity.setEndDate(LocalDateTime.now());
		}
		if(StringUtils.hasText(params.getMemo())) {
			if(StringUtils.isEmpty(entity.getRemark())) {
				entity.setRemark(params.getMemo());
			}else {
				entity.setRemark(entity.getRemark()+"/n"+params.getMemo());
			}
		}
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.setMemo(params.getMemo());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		
		if(YNEnum.NO.getCode().equals(params.getStatus())) {
			OrderInfo order=orderInfoService.getById(entity.getOrderSn());
			order.setRefundFund(order.getRefundFund().subtract(entity.getFund()));
			order.addEditParam(userInfo);
			orderInfoService.updateById(order);
			
			OrderItem orderItem=orderItemService.getById(entity.getOrderItemId());
			orderItem.setReturnedQuantity(orderItem.getReturnedQuantity()-entity.getQuantity());
			orderItemService.updateById(orderItem);
		}else if(subFund!=null){
			OrderInfo order=orderInfoService.getById(entity.getOrderSn());
			order.setRefundFund(order.getRefundFund().subtract(subFund));
			order.addEditParam(userInfo);
			orderInfoService.updateById(order);
		}

		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}
	
	/**退款*/
	@Transactional
	@Override
	public void refund(OrderReturnsRefundParam params, LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		OrderReturns entity=orderReturnsService.getById(params.getSn());
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		if(!userInfo.getCompanyNo().equals(entity.getMainCompanyNo())) {
			throw new BusinessException(MallErrorEnum.Order_After_User_Error);
		}
		if(!OrderReturnStateEnum.ORFPS_Receiving.getCode().equals(entity.getState())   ) {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		OrderInfo orderInfo=orderInfoService.getById(entity.getOrderSn());
		if(null == orderInfo) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		
		//原路返回
		if(PayMethodEnum.PM_Online_Pay.getCode().equals(orderInfo.getPaymentMethod())) {
			//线上支付
			OrderPayment orderPayment=orderPaymentService.getOne(new QueryWrapper<OrderPayment>()
					.eq("type", PayActionTypeEnum.PA_Pay.getCode())
					.eq("biz_order_type", IRelBusiType.Order_ObjType)
					.eq("biz_order_sn", entity.getOrderSn())
					.eq("payment_state", PayStateEnum.Pay_Success.getCode())
					);
			if(orderPayment!=null) {
				if(PayMethodEnum.PM_Online_Pay.getCode().equals(orderPayment.getPaymentMethod())) {
					OrderPayment refundPayment=new OrderPayment();
					refundPayment.setType(PayActionTypeEnum.PA_Refund.getCode());
					refundPayment.setPaySn(ShopNoUtils.getRefundSn());
					refundPayment.setBizOrderType(IRelBusiType.Order_Returns_ObjType);
					refundPayment.setBizOrderSn(entity.getSn());
					refundPayment.setCustNo(entity.getCompanyNo());
					refundPayment.setPayerUserId(entity.getUserId());
					refundPayment.setPaymentMethod(orderPayment.getPaymentMethod());
					refundPayment.setPaymentChannel(orderPayment.getPaymentChannel());
					refundPayment.setFund(entity.getFund());
					refundPayment.setFee(BigDecimal.ZERO);
					refundPayment.setTotalFund(refundPayment.getFund().add(refundPayment.getFee()));
					refundPayment.setPaymentState(PayRefundStateEnum.Refund_Ing.getCode());
					refundPayment.setPaymentApplyDate(LocalDateTime.now());
					refundPayment.setCheckState(YNEnum.NO.getCode());
					refundPayment.addCreateParam(userInfo);
					orderPaymentService.save(refundPayment);
					shopOnlinePayService.payRefundApply(refundPayment.getCustNo(),refundPayment.getPaymentChannel(), orderPayment.getPaySn(), orderPayment.getTotalFund(),refundPayment.getPaySn(), entity.getFund(), "");
				}
			}
		}else if(PayMethodEnum.PM_Point_Pay.getCode().equals(orderInfo.getPaymentMethod())) {
			//积分支付-退款
			AcctOpRequest  pointParams=new AcctOpRequest();
			pointParams.setUserId(entity.getUserId());
			pointParams.setType(AcctTypeEnum.Point_Acct.getCode());
			pointParams.setIsAcctDetail(YNEnum.YES.getCode());
			pointParams.setOpType(AcctOpTypeEnum.Add_Acct.getCode());
			pointParams.setRelObjType(IRelBusiType.Order_Returns_ObjType);
			pointParams.setRelObjNo(entity.getSn());
			pointParams.setFundOp(entity.getFund());
			pointParams.setFundTax(BigDecimal.ZERO);
			pointParams.setRelBizName(entity.getName());
			pointParams.setRelDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			pointParams.setBusiType("订单退款");
			pointParams.setMemo("退货退款");
			pointParams.setOpUserId(userInfo.getId());
			pointParams.setOpIp(userInfo.getIp());
			accountRemoteService.opAcct(pointParams);
			
			
		}
		
		
		if(PayMethodEnum.PM_Online_Pay.getCode().equals(orderInfo.getPaymentMethod())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Refund.getCode());
		}else if(PayMethodEnum.PM_Point_Pay.getCode().equals(orderInfo.getPaymentMethod())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Complete.getCode());
			entity.setEndDate(LocalDateTime.now());
		}
		if(StringUtils.hasText(params.getMemo())) {
			if(StringUtils.isEmpty(entity.getRemark())) {
				entity.setRemark(params.getMemo());
			}else {
				entity.setRemark(entity.getRemark()+"/n"+params.getMemo());
			}
		}
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		//判断是否全部退货
		if(OrderReturnStateEnum.ORFPS_Complete.getCode().equals(entity.getState())) {
			this.checkReturnFull(entity.getOrderSn(),userInfo);
		}
		
		//log
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.setMemo(params.getMemo());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}
	
	
	/**判断是否全部退货*/
	private void checkReturnFull(String orderSN,LoginSimpleUserInfo userInfo) {
		int count= orderItemService.count(new QueryWrapper<OrderItem>()
				.eq("order_sn", orderSN)
				.apply("quantity <> returned_quantity")
				);
		if(count==0) {
			OrderInfo order=orderInfoService.getById(orderSN);
			order.setStatus(OrderStateEnum.OSE_Close.getCode());
			order.setCloseDate(LocalDateTime.now());
			order.setHandleDate(LocalDateTime.now());
			order.setHandleUserId(userInfo.getId());
			order.addEditParam(userInfo);
			orderInfoService.updateById(order);
		}
	}

	/**第三方支付退款回调处理*/
	@Transactional
	@Override
	public void callbackRefund(String sn, String refundSN, String refundState, String thirdrefundState,
			PayConfirmWay confirmChannel,LoginSimpleUserInfo userInfo) {
		OrderPayment orderPayment=orderPaymentService.getOne(new QueryWrapper<OrderPayment>()
				.eq("pay_sn", refundSN));
		if(orderPayment==null) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		
		//支付流水
		if(StringUtils.isEmpty(orderPayment.getPaymentConfirmChannel())
				|| confirmChannel.getCode().equals(orderPayment.getPaymentConfirmChannel())
				|| Integer.parseInt(confirmChannel.getCode()) > Integer.parseInt(orderPayment.getPaymentConfirmChannel())
				) {
			orderPayment.setPaymentState(refundState);
			orderPayment.setPaymentConfirmDate(LocalDateTime.now());
			orderPayment.setPaymentConfirmChannel(confirmChannel.getCode());
			orderPayment.setThirdState(thirdrefundState);
			orderPayment.addEditParam(userInfo);
			orderPaymentService.updateById(orderPayment);
		}else {
			return;
		}
		
		OrderReturns entity=orderReturnsService.getById(sn);
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
//		if(!OrderReturnStateEnum.ORFPS_Refund.getCode().equals(entity.getState())   ) {
//			throw new BusinessException(ShopErrorEnum.Order_State_Op_Not);
//		}
		
		
		//退款退货
		if(PayRefundStateEnum.Refund_Success.getCode().equals(orderPayment.getPaymentState())) {
			entity.setState(OrderReturnStateEnum.ORFPS_Complete.getCode());
			entity.setEndDate(LocalDateTime.now());
		}
		if(PayRefundStateEnum.Refund_Fail.getCode().equals(orderPayment.getPaymentState())
				|| PayRefundStateEnum.Refund_Close.getCode().equals(orderPayment.getPaymentState())) {
			entity.setState(OrderReturnStateEnum.ORFPS_RefundFail.getCode());
		}
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		//log
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		
		//判断是否全部退货
		if(OrderReturnStateEnum.ORFPS_Complete.getCode().equals(entity.getState())) {
			this.checkReturnFull(entity.getOrderSn(),userInfo);
		}
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}

	
	/**退款完成*/
	@Override
	public void complete(String sn,LoginSimpleUserInfo userInfo) {
		OrderReturns entity=orderReturnsService.getById(sn);
		if(null == entity) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
		if(!OrderReturnStateEnum.ORFPS_Refund.getCode().equals(entity.getState())   ) {
			throw new BusinessException(MallErrorEnum.Order_State_Op_Not);
		}
		
		entity.setState(OrderReturnStateEnum.ORFPS_Complete.getCode());
		entity.setEndDate(LocalDateTime.now());
		entity.setHandleUserId(userInfo.getId());
		entity.setHandleDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		orderReturnsService.updateById(entity);
		
		OrderLog log=new OrderLog();
		log.setOrderType(IRelBusiType.Order_Returns_ObjType);
		log.setSn(entity.getSn());
		log.setState(entity.getState());
		log.addCreateParam(userInfo);
		orderLogService.save(log);
		
		//判断是否全部退货
		this.checkReturnFull(entity.getOrderSn(),userInfo);
		//MQ
		shopOrderProducer.onReturnOrderChange(entity);
	}

	
	/**获取*/
	@Override
	public OrderReturnsModel get(String sn) {
		OrderReturns entity=orderReturnsService.getById(sn);
		if(entity==null) {
			throw new BusinessException(MallErrorEnum.Order_After_Returns_NotExist);
		}
//		List<OrderLog> records=orderLogService.list(new QueryWrapper<OrderLog>()
//				.eq("order_type", ShopObjType.Order_Returns_ObjType).eq("sn", sn).orderByAsc("cdt"));
		OrderReturnsModel data= ShopOrderConvertUtils.getOrderReturns(entity, null,null);
		return data;
	}
	
	
}
